<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        form {
            width: 400px;
            height: 250px;
            box-shadow: 0px 0px 5px #000;
            margin: auto;
            margin-top: 100px;
            padding: 20px;

        }

        form p {
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
        }
    </style>
  </head>

  <body>
    <form action="">
      <p>
        <label for="">用户名：</label>
        <input type="text" id="username">
      </p>
      <p>
        <label for="">密码：</label>
        <input type="text" id="password">
      </p>
      <p>
        <button>登录</button>
      </p>
    </form>

    <script type="module">
      import {ajax} from './utils.js'
        // 如果已经登录 就不要展示登录页面直接跳转到用户页面即可
        let user = JSON.parse(localStorage.getItem('user'));
        if (user) {
            location.href = './mine.html';
        }

        let form = document.querySelector('form');
        let username = form.querySelector('#username');
        let password = form.querySelector('#password');

        form.onsubmit = function (e) {
            e.preventDefault();
            let name = username.value;
            let pass = password.value;

            ajax({
                url: '/api/login',
                type: 'get',
                data: { username: name, password: pass },
                success(res) {
                    if (res.code != 200) {
                        alert(res.msg);
                        username.value = '';
                        password.value = '';
                        return
                    }
                    localStorage.setItem('user', JSON.stringify(res.data))
                    location.href = './mine.html';
                }
            })
        }
    </script>
  </body>

</html>